//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
package com.saasovation.identityaccess.infrastructure.persistence;

import com.saasovation.identityaccess.domain.model.identity.TenantId;
import com.saasovation.identityaccess.domain.model.identity.User;
import com.saasovation.identityaccess.domain.model.identity.UserRepository;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.query.Query;

import java.util.Collection;

public class HibernateUserRepository implements UserRepository {
    private final SessionFactory sessionFactory;

    public HibernateUserRepository(SessionFactory sessionFactory) {
        super();
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void add(User aUser) {
        try {
            this.getCurrentSession().persist(aUser);
        } catch (ConstraintViolationException e) {
            throw new IllegalArgumentException("User is not unique.", e);
        }
    }

    @Override
    public Collection<User> allSimilarlyNamedUsers(TenantId aTenantId,
                                                   String aFirstNamePrefix,
                                                   String aLastNamePrefix) {
        if (aFirstNamePrefix.endsWith("%") || aLastNamePrefix.endsWith("%")) {
            throw new IllegalArgumentException("Name prefixes must not include %.");
        }
        Query<User> query = this.getCurrentSession().createQuery(
                "from com.saasovation.identityaccess.domain.model.identity.User as _obj_ "
                        + "where _obj_.tenantId = :tenantId "
                        + "and _obj_.person.name.firstName like :firstName "
                        + "and _obj_.person.name.lastName like :lastName", User.class);
        query.setParameter("tenantId", aTenantId);
        query.setParameter("firstName", aFirstNamePrefix + "%");
        query.setParameter("lastName", aLastNamePrefix + "%");
        return query.list();
    }

    @Override
    public void remove(User aUser) {
        this.getCurrentSession().remove(aUser);
    }

    @Override
    public User userFromAuthenticCredentials(TenantId aTenantId,
                                             String aUsername,
                                             String anEncryptedPassword) {
        Query<User> query = this.getCurrentSession().createQuery(
                "from com.saasovation.identityaccess.domain.model.identity.User as _obj_ "
                        + "where _obj_.tenantId = :tenantId "
                        + "and _obj_.username = :username "
                        + "and _obj_.password = :passwrd", User.class);
        query.setParameter("tenantId", aTenantId);
        query.setParameter("username", aUsername);
        query.setParameter("passwrd", anEncryptedPassword);
        return query.uniqueResult();
    }

    @Override
    public User userWithUsername(TenantId aTenantId, String aUsername) {
        Query<User> query = this.getCurrentSession().createQuery(
                "from com.saasovation.identityaccess.domain.model.identity.User as _obj_ "
                        + "where _obj_.tenantId = :tenantId "
                        + "and _obj_.username = :userName", User.class);
        query.setParameter("tenantId", aTenantId);
        query.setParameter("userName", aUsername);
        return query.uniqueResult();
    }

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }
}
